<template>
	<swiper class="home-swiper" @change="change" :current="activeIndex">
		<swiper-item v-for="(item,index) in tablist " :key="index" class="swiper-item">
			<list-item :list="listCatchData[index]" @loadmore="loadmore" :load = "load[index]"></list-item>
		</swiper-item>
	</swiper>
</template>

<script>
	import listItem from './list-item.vue'
	export default {
		components: {
			listItem
		},
		props: {
			tablist: {
				type: Array,
				default () {
					//为什么用函数方式？
					return []
				}
			},
			activeIndex: {
				type: Number,
				default: 0
			}
		},
		name: "list",
		data() {
			return {
				load:{},
				pageSize:10,
				list: [],
				//解决反复拉取数据更新刷新卡顿的问题
				listCatchData: {},
				
				// listCatchData的数据结构
				// listCatchData:{
				// 	0:[],
				// 	1:[]...
				// }
			};
		},
		created() {
			//tab 还没有赋值
			// this.getList(0)
			uni.$on('update_article',(e)=>{
				console.log(e)
				if(e==='follow'){
					this.listCatchData = {};
					this.load = {}
					this.getList(this.activeIndex)
				}

			})
		},
		watch:{
			tablist(newVal){
				if(newVal.length===0) return ;
				//置空，防止数据重复加载导致Key重复 1 
				this.listCatchData = {};
				this.load = {};
				this.getList(this.activeIndex)
			}
		},
		methods: {
			loadmore(){
				if(this.load[this.activeIndex].loading === "noMore") return
				this.load[this.activeIndex].page ++;
				this.getList(this.activeIndex)
			},
			change(e) {
				const {
					current
				} = e.detail;
				this.$emit('change', current)
				// 数据不存在或长度为0 才去请求数据
				if(!this.listCatchData[current] || this.listCatchData[current].length=== 0){
					this.getList(current)
				}
			},
			getList(current) {
				//对page 做初始化
				if(!this.load[current]){
					this.load[current] = {
						page :1 ,
						loading:"loading"
					}
				}
				this.$api.get_list({
					name: this.tablist[current].name,
					page:this.load[current].page,
					pageSize:this.pageSize
				}).then((res) => {
					const {
						data
					} = res;
					if(data.length == 0){
						//当data.length 为0 时 说明没有数据要再继续加载了
						let oldLoad = {};
						oldLoad.loading = 'noMore';
						oldLoad.page = this.load[current].page
						this.$set(this.load,current,oldLoad)
						this.$forceUpdate()
						return 
					}
					// ???这是什么逻辑
					let oldList = this.listCatchData[current] || [];
					oldList.push(...data)
					// console.log(data)
					// this.list = data
					// this.listCatchData[current] = data
					//数据懒加载  当传入不同的current请求不同的数据，拿到数据后，this.$set让视图更新  解决滑动时数据卡顿的问题
					this.$set(this.listCatchData,current,oldList)
				})
			}
		}
	}
</script>

<style lang="scss">
	.home-swiper {
		height: 100%;

		.swiper-item {
			height: 100%;
			overflow: hidden;

			.list-scroll {
				height: 100%;
			}
		}
	}
</style>
